using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

namespace WeatherRouter
{
    public sealed class LogManager : IDisposable
    {
        private static readonly string LOG_FILENAME = "coral.log";

        private FileStream _fileStream;
        private TextWriter _textWriter;
        private string _servicePath;

        private static LogManager _instance;

        /// <summary>
        /// Private ctor to inforce singleton pattern.
        /// </summary>
        static LogManager()
        {
        }

        /// <summary>
        /// Static initializer.
        /// </summary>
        private LogManager()
        {
            _servicePath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);

            string fileName = _servicePath + @"\" + LOG_FILENAME;
            _fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write);
            _textWriter = new StreamWriter(_fileStream, Encoding.GetEncoding(1251));
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_textWriter != null)
            {
                _textWriter.Close();
            }
        }

        #endregion

        /// <summary>
        /// Returns the single instance of this object.
        /// </summary>
        public static LogManager Instance
        {
            get
            {
                // Lazy initialization
                if (_instance == null)
                {
                    _instance = new LogManager();
                }
                return _instance;
            }
        }

        public static void Info(string entry)
        {
            LogManager.Instance.WriteHelper(entry);
        }

        public static void Info(string entry, params object[] args)
        {
            LogManager.Instance.WriteHelper(entry, args);
        }

        public static void Error(string entry)
        {
            LogManager.Instance.WriteHelper(entry);
        }

        public static void Error(string entry, params object[] args)
        {
            LogManager.Instance.WriteHelper(entry, args);
        }

        public static void Warning(string entry)
        {
            LogManager.Instance.WriteHelper(entry);
        }

        public static void Warning(string entry, params object[] args)
        {
            LogManager.Instance.WriteHelper(entry, args);
        }

        private void WriteHelper(string entry)
        {
            _textWriter.WriteLine(string.Format("[{0:G}] - {1}", DateTime.Now.ToUniversalTime(), entry));
            _textWriter.Flush();
        }

        private void WriteHelper(string entry, params object[] args)
        {
            WriteHelper(string.Format("[{0:G}] - {1}", DateTime.Now.ToUniversalTime(), string.Format(entry, args)));
        }
    }
}
